package com.lgy.download;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class DownloadUtils {
	private static Logger logger = LoggerFactory.getLogger(DownloadUtils.class);
	/**
	 * 获取远程文件的大小Content-length的长度
	 */
	public static long getRemoteFileSize(String remoteFileUrl) throws IOException {
		HttpURLConnection httpConnection = (HttpURLConnection) new URL(remoteFileUrl).openConnection();
		httpConnection.setRequestMethod("HEAD");
		int responseCode = httpConnection.getResponseCode();
		if (responseCode == 200) {
			Map<String, List<String>> fields = httpConnection.getHeaderFields();
			Set<String> keySet = fields.keySet();
			for (String sHeader : keySet) {
				if (sHeader != null && sHeader.equals("Content-Length")) {
					logger.debug("文件大小ContentLength:" + httpConnection.getContentLength());
					Long length = Long.parseLong(httpConnection.getHeaderField(sHeader));
					return length;
				}
			}
			logger.debug("Content-Length is not exist!");
			return -1;
		} else {
			logger.debug("Web服务器响应错误!");
			return -1;
		}
	}

	/**
	 * 获取远程文件的类型Content-Type
	 * 
	 */
	public static String getRemoteFileType(String remoteFileUrl) throws IOException {
		HttpURLConnection httpConnection = (HttpURLConnection) new URL(remoteFileUrl).openConnection();
		httpConnection.setRequestMethod("HEAD");
		int responseCode = httpConnection.getResponseCode();
		if (responseCode == 200) {
			Map<String, List<String>> fields = httpConnection.getHeaderFields();
			Set<String> keySet = fields.keySet();
			for (String sHeader : keySet) {
				if (sHeader != null && sHeader.equals("Content-Type")) {
					logger.debug("文件大小Content-Type:" + httpConnection.getHeaderField(sHeader));
					return httpConnection.getHeaderField(sHeader);
				}
			}
			logger.debug("文件大小Content-Type is not exist");
			return null;
		} else {
			logger.debug("Web服务器响应错误!");
			return null;
		}
	}
	
	/**
	 * 
	 * <p>Title: getBytesFromFile</p>
	 * <p>Description: 将文件转化为字节流</p>
	 * @param file
	 * @return
	 * @throws IOException
	 */
	@SuppressWarnings("resource")
	public  static byte[] getBytesFromFile(File file) throws IOException {
        InputStream is = new FileInputStream(file);
        // 获取文件大小
        long length = file.length();
        if (length > Integer.MAX_VALUE) {
            // 文件太大，无法读取
        	throw new IOException("File is to large "+file.getName());
        }
        // 创建一个数据来保存文件数据
        byte[] bytes = new byte[(int)length];
        // 读取数据到byte数组中
        int offset = 0;
        int numRead = 0;
        while (offset < bytes.length && (numRead=is.read(bytes, offset, bytes.length-offset)) >= 0) {
            offset += numRead;
        }

        // 确保所有数据均被读取
        if (offset < bytes.length) {
            throw new IOException("Could not completely read file "+file.getName());
        }
        // Close the input stream and return bytes
        is.close();
        return bytes;
    }
}
